package com.spring.serviceimp.product;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.upload.FormFile;

import com.common.Constant;
import com.common.PicUpload;
import com.hibernate.dao.product.ProductDao;
import com.hibernate.pojo.Product;
import com.spring.service.product.ProductService;
import com.struts.form.ProductForm;

public class ProductServiceImp implements ProductService
{
	private ProductDao productDao=null;

	public Map findProducts(int page,int productleibieID)
	{
		return productDao.findProducts(page, productleibieID);
	}
	
	/**
	 * save product
	 */
	public Long saveProduct(ProductForm productform)
	{
		Product product=new Product();
		//image process
		FormFile ff=productform.getProduct_pic();
		String newfilename="";
		if(ff.getFileSize()>0)
		{
			//return folder name
			String datefile=new PicUpload().createFolder(Constant.PRODUCT_UPLOAD_PIC);
			//database save path
			newfilename=Constant.PRODUCT_DATABASE_SAVEPATH+datefile+"/";
			//save pic,return pic name
			newfilename+=new PicUpload().picUpload(Constant.PRODUCT_UPLOAD_PIC+datefile, ff);
		}
		try
		{
			BeanUtils.copyProperties(product, productform);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		//write image to productDAO
		if(ff.getFileSize()>0)
			product.setProduct_pic(newfilename);
		return productDao.saveProduct(product);
	}
	
	/**
	 * edit product
	 */
	public Map updateProduct(ProductForm productform)
	{
		FormFile file = productform.getProduct_pic();
		String newfilename="";
		if(file.getFileSize()>0)
		{
			//return folder name
			String datefile=new PicUpload().createFolder(Constant.PRODUCT_UPLOAD_PIC);
			//database save path
			newfilename=Constant.PRODUCT_DATABASE_SAVEPATH+datefile+"/";
			//save pic,return pic name
			newfilename+=new PicUpload().picUpload(Constant.PRODUCT_UPLOAD_PIC+datefile, file);
		}
		List list= productDao.updateProduct(productform,newfilename);
		Map list_temp;
		Map map=new HashMap();
		for(int i=0;i<list.size();i++)
		{
			list_temp=(Map)list.get(i);
			if(i==0)
				map.put("product_id", list_temp.get("productId"));
			Map map1=new HashMap();
			map1.put("atrribute_value", list_temp.get("atrribute_value"));
			map1.put("atrributeId", list_temp.get("ppaId"));
			map.put(list_temp.get("atrribute_name"), map1);
		}
		return map;
	}
	
	
	public List updateProductView(Long id)
	{
		return productDao.updateProductView(id);
	}
	
	public boolean updateProductAudit(ProductForm productform)
	{
		return productDao.updateProductAudit(productform);
	}
	
	public boolean deleteProduct(Long id)
	{
		return productDao.deleteProduct(id);
	}
	
	public ProductDao getProductDao() {
		return productDao;
	}

	public void setProductDao(ProductDao productDao) {
		this.productDao = productDao;
	}
}
